'''
Created on Nov 8, 2012

@author: peng
'''

import os
import MySQLdb

BELUGA_DB_CONFIG = {'host': '10.42.133.171',
                    'user': 'dev_analysis',
                    'password': 'analysis_dev_pwd',
                    'db': 'beluga_analysis',
                    'port': 3306}


class MySQLdbWrapper:

    conn = None

    def connect(self):
        self.conn = MySQLdb.connect(host=BELUGA_DB_CONFIG['host'],
                                    user=BELUGA_DB_CONFIG['user'],
                                    passwd=BELUGA_DB_CONFIG['password'],
                                    db=BELUGA_DB_CONFIG['db'],
                                    port=BELUGA_DB_CONFIG['port'])
        self.conn.set_character_set('utf8')
        self.conn.autocommit(True)

    def cursor(self):
        try:
            # if not self.conn:
            self.connect()
            return self.conn.cursor()
        except MySQLdb.OperationalError:
            self.connect()
            return self.conn.cursor()

_db = MySQLdbWrapper()


def get_data(sql):
    try:
        cursor = _db.cursor()
        cursor.execute(sql)
        data = cursor.fetchall()
        return data
    finally:
        cursor.close()


sql_channel = \
'''
select app_key, app_version, count(*)
from dev_basic
where date(a.first_launch_time)<'2012-10-01'
group by app_version
'''

path = '/mnt/export/'

channels_dict = {}
versions_dict = {}


def flush(data_list):
    if len(data_list) == 0:
        return
    f = open(os.path.join('', 'all_version'), 'a+')
    data = '\n'.join(data_list)
    f.write(data)
    f.write('\n')
    f.close()


def export_basic():
    sql = 'select id, channel from dim_channel_basic'
    rows = get_data(sql)
    for row in rows:
        channels_dict[row[0]] = row[1]

    sql = 'select id, app_version from dim_app_version_basic'
    rows = get_data(sql)
    for row in rows:
        versions_dict[row[0]] = row[1]


def export_channels():
    data_list = []
    rows = get_data(sql_channel)
    for row in rows:
        if row[1] in versions_dict:
            line = '\t'.join([row[0], '20120930', '-', '0', row[1], '-', str(row[1])])
            data_list.append(line)
    flush(data_list)

